package com.easthome.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easthome.auth.service.SysUserService;


import com.easthome.common.handler.EasthomeException;
import com.easthome.model.system.SysUser;


import com.easthome.security.custom.CustomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;
 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username));
        if(null == sysUser) {
            throw new EasthomeException("用户名不存在！",201);
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        List<String> buttons = sysUserService.findButtonsByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> collect = buttons.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        System.out.println(collect);
        return new CustomUser(sysUser, collect);
    }
}